package com.user_Chan.Blockchain.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Chan
 * @title: Http_Utils
 * @projectName C200603_Tu_Blockchain
 * @desc:   封装网络请求，返回网络数据
 * @date 2021/12/14 11:27 下午
 */
public class Http_Utils {

   /**
    　　* @description: Get请求方法并返回结果
    　　* @param      path请求资源路径
    　　* @return ${请求结果}
    　　* @author ${Chan}
    　　* @date 2021/12/15 12:37 上午
    　　*/
    //请求路径
    public static String Get(String path){
        //空行
        String line = "";
        String results = "";

        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;

        try {
            URL url = new URL(path);
            //建立连接
            URLConnection conn = url.openConnection();
            //进行连接
            conn.connect();
            //字符流
            inputStream =  conn.getInputStream();

            //？能否把InputStreamReader一起关闭
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader= new BufferedReader(inputStreamReader);
            //while 循环读取
            while ((line = bufferedReader.readLine()) != null){
                results += line;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                if(bufferedReader != null){
                    bufferedReader.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
                if(inputStreamReader != null){
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return results;

        }
    }
}
